package com.boruan.shengtangfeng.core.service.impl;

import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.dto.JobConditionDto;
import com.boruan.shengtangfeng.core.dto.JobDto;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.enums.QuestionType;
import com.boruan.shengtangfeng.core.service.ISchoolService;
import com.boruan.shengtangfeng.core.utils.DateUtils;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.GradeUtil;
import com.boruan.shengtangfeng.core.vo.ClassAndVo;
import com.boruan.shengtangfeng.core.vo.MyJoinClassNameVo;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
public class SchoolService implements ISchoolService {


    @Autowired
    private ISchoolDao schoolDao;
    @Autowired
    private IClassAndDao classAndDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IClassMembersDao classMembersDao;
    @Autowired
    private IInformDao informDao;
    @Autowired
    private IClassParameterDao classParameterDao;
    @Autowired
    private GradeUtil gradeUtil;
    @Autowired
    private IGroupChatDao groupChatDao;
    @Autowired
    private IJobDao jobDao;
    @Autowired
    private ISubjectDao subjectDao;
    @Autowired
    private IUserJobDao userJobDao;
    @Autowired
    private IQuestionDao questionDao;
    @Autowired
    private IJobQuestionDao jobQuestionDao;
    @Autowired
    private IJobParameterDao jobParameterDao;


    @Override
    public School findById(Long id) {
        return schoolDao.unique(id);
    }

    @Override
    public GlobalReponse<PageQuery<School>> getSchools(PageQuery<School> pageQuery) {
        schoolDao.pageQuery(pageQuery);
        return GlobalReponse.success(pageQuery);
    }


    @Override
    public GlobalReponse<PageQuery<ClassAndVo>> getClassAnd(PageQuery<ClassAnd> pageQuery,Long userId) {
        classAndDao.pageQuery(pageQuery);
        List<ClassAnd> list = pageQuery.getList();
        List<ClassAndVo> listVo = new ArrayList<>();
        list.forEach( v->{
            ClassAndVo vo = new ClassAndVo();
            vo.setClassId(v.getId());
            vo.setClassName(v.getName());
            vo.setClassNum(v.getClassNum());
            //查询创建人
            User creater = userDao.createLambdaQuery().andEq(User::getId, Long.valueOf(v.getCreateBy())).unique();
            vo.setCreateName(creater.getName());
            vo.setCreateImage(creater.getHeadImage());
            vo.setCreateId(creater.getId());
            GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, v.getId()).andEq(GroupChat::getIsDeleted, false).single();
            if (groupChat.getTencentId()!=null){
                vo.setTencentId(groupChat.getTencentId());
            }
            //查询班级人数
            Long memberNum = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId,v.getId()).count();
            vo.setMemberNum(memberNum);
            //查询学校信息
            School school = schoolDao.unique(v.getSchoolId());
            vo.setSchoolId(school.getId());
            vo.setSchoolName(school.getName());
            vo.setProvince(school.getProvince());
            vo.setCity(school.getCity());
            vo.setCounty(school.getCounty());
            //处理学年格式
            ClassParameter classParam =classParameterDao.createLambdaQuery().andEq(ClassParameter::getId,1).unique();
            String schoolYear = gradeUtil.getGrade(Integer.valueOf(v.getSchoolYear()),classParam.getSpringTime(),classParam.getAutumnTime());
            vo.setGradeName(schoolYear);
            vo.setSchoolYear(v.getSchoolYear());
            //判断是否已加入
            ClassMembers classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId,v.getId()).andEq(ClassMembers::getUserId,userId).andEq(ClassMembers::getIsDeleted,0).single();
            if(classMembers!=null){
                vo.setIsJoin(true);
            }else{
                vo.setIsJoin(false);
            }
            listVo.add(vo);
        });

        pageQuery.setList(listVo);
        return GlobalReponse.success(pageQuery);
    }

    @Override
    public List<ClassAnd> myClassAnd(Long userId) {
        List<ClassAnd> list = classAndDao.getClassByUid(userId);
        return list;
    }

    @Override
    public GlobalReponse<PageQuery<JobDto>> getJobListById(JobConditionDto jobConditionDto, Long userId) {
        PageQuery<Job> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(jobConditionDto.getPageNo());
        pageQuery.setPageSize(10);
        pageQuery.setPara("classId", jobConditionDto.getClassId());
        pageQuery.setPara("pushTime", jobConditionDto.getPushTime());
        pageQuery.setPara("entTime", jobConditionDto.getEntTime());
        pageQuery.setPara("subjectName", jobConditionDto.getSubjectName());
        pageQuery.setPara("sort", jobConditionDto.getSort());
        pageQuery.setPara("userId", userId);
        pageQuery.setPara("notComplete", jobConditionDto.getNotComplete());
        if (jobConditionDto.getPushTime()!=null && jobConditionDto.getPushTime()==5){
            pageQuery.setPara("startTime", jobConditionDto.getStartTime());
            pageQuery.setPara("finishTime", jobConditionDto.getFinishTime());
        }
        if (jobConditionDto.getPushTime()!=null && jobConditionDto.getPushTime()==4){
            ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
            //判断上下学期
            String now = new SimpleDateFormat("MM-dd").format(new Date());
            String spring = classParam.getSpringTime();
            String autumn = classParam.getAutumnTime();
            Date nowTime = null;
            Date springTime = null;
            Date autumnTime = null;
            try {
                nowTime = DateUtils.parseDate(now, "MM-dd");
                springTime = DateUtils.parseDate(spring, "MM-dd");
                autumnTime = DateUtils.parseDate(autumn, "MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            int yearD = cal.get(Calendar.YEAR);

            if (nowTime.after(autumnTime) && nowTime.before(springTime)) {
                pageQuery.setPara("startTime", yearD+"-"+classParam.getAutumnTime());
                pageQuery.setPara("finishTime",  yearD+"-"+classParam.getSpringTime());
            } else {
                pageQuery.setPara("startTime", yearD+"-"+classParam.getSpringTime());
                pageQuery.setPara("finishTime", yearD+1+"-"+classParam.getAutumnTime());

            }
        }
        jobDao.getJobListById(pageQuery);

        List<JobDto> dtos = new ArrayList<>();
        for (Job job : pageQuery.getList()) {
            JobDto jobDto = new JobDto();
            jobDto.setJobId(job.getId());
            jobDto.setJobName(job.getName());
            jobDto.setDeadline(job.getDeadline());
            jobDto.setDeadlineTime(job.getDeadline().getTime());
            User user = userDao.unique(Long.valueOf(job.getCreateBy()));
            jobDto.setPusherId(user.getId());
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, jobConditionDto.getClassId()).andEq(ClassMembers::getUserId, user.getId()).andEq(ClassMembers::getIsDeleted, false).single();
            if (single!=null){
                jobDto.setPusherName(single.getNickname());
            }else {
                jobDto.setPusherName(user.getName());
            }
            jobDto.setPusherImage(user.getHeadImage());
            Subject subject = subjectDao.unique(job.getSubjectId());
            jobDto.setSubjectName(subject.getName());

            //答题状态
            UserJob userJob = userJobDao.createLambdaQuery().andEq(UserJob::getClassId,jobConditionDto.getClassId()).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getUserId,userId).andEq(UserJob::getIsDeleted, false).single();
            if (userJob!=null && userJob.getStatus()!=null){
                jobDto.setStatus(userJob.getStatus());
                if (!userJob.getStatus().equals(0)){
                    List<Question> questions = questionDao.getJobQuestion(job.getId());
                    List<QuestionType> types = questions.stream().map(Question::getType).collect(Collectors.toList());
                    ArrayList<Integer> integers = new ArrayList<>();
                    for (QuestionType type : types) {
                        Integer value = type.getValue();
                        integers.add(value);
                    }
                    if (!integers.contains(1) && !integers.contains(2)){
                        jobDto.setStatus(-1);
                    }
                    if (userJob.getScore()!=null){
                        jobDto.setScore(userJob.getScore().stripTrailingZeros().toPlainString());
                    }
                }else {
                   jobDto.setStatus(0);
                }
            }else {
                jobDto.setStatus(0);
            }
            //是否过截止时间
            if (new Date().getTime()>job.getDeadline().getTime()){
                jobDto.setIsDeadline(true);
            }else {
                jobDto.setIsDeadline(false);
            }
            JobParameter jobParameter = jobParameterDao.createLambdaQuery().andEq(JobParameter::getIsDeleted, false).single();
            BigDecimal multiply = job.getScore().multiply(jobParameter.getAccuracy().divide(new BigDecimal(100))).setScale(2);
            jobDto.setFractionalLine(multiply);
            dtos.add(jobDto);
        }
        PageQuery<JobDto> dtoPageQuery = new PageQuery<>();
        dtoPageQuery.setList(dtos);
        dtoPageQuery.setPageSize(pageQuery.getPageSize());
        dtoPageQuery.setPageNumber(pageQuery.getPageNumber());
        dtoPageQuery.setTotalRow(pageQuery.getTotalRow());

        return GlobalReponse.success(dtoPageQuery);
    }

    /**
     * 发布讲一讲时候获取我加入的班级
     *
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<List<MyJoinClassNameVo>> getMyJoinClassName(Long userId) {
        List<MyJoinClassNameVo> vos = new ArrayList<>();
        List<ClassMembers> classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).select();
        for (ClassMembers classMember : classMembers) {
            MyJoinClassNameVo vo = new MyJoinClassNameVo();
            ClassAnd classAnd = classAndDao.unique(classMember.getClassId());
            if (classAnd.getStatus().equals(0)){
                vo.setId(classAnd.getId());
                vo.setClassName(classAnd.getSchoolYear()+"级"+classAnd.getName());
                vos.add(vo);
            }
        }
        return  GlobalReponse.success(vos);
    }

}
